package com.zhanglijie.improve.atomic.six;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

import co.paralleluniverse.strands.dataflow.Var;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/10 0010 19:10
 * 性能对比
 */
public class TestPerformance {
    static int threadcount = 100;
    static int testNum = 10000;

    static AtomicLong atomicLong = new AtomicLong(0);
    static LongAdder longAdder = new LongAdder();

    public static void main(String[] args) throws InterruptedException {
        testAtomicLong(threadcount,testNum);
        testLongAddr(threadcount,testNum);
    }

    private static void testLongAddr(int threadcount, int testNum) throws InterruptedException {
        long cur = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(threadcount);
        for (int i = 0; i < threadcount; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < testNum; i1++) {
                    longAdder.increment();
                }
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println("long addr result "+longAdder.longValue());
        System.out.println("long addr 耗时"+(System.currentTimeMillis()-cur));
    }


    private static void testAtomicLong(int threadcount, int testNum) throws InterruptedException {
        long cur = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(threadcount);
        for (int i = 0; i < threadcount; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < testNum; i1++) {
                    atomicLong.incrementAndGet();
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        System.out.println("atomic Long result is "+atomicLong.get());
        System.out.println("long addr 耗时"+(System.currentTimeMillis()-cur));
    }


}
